package com.csdj.sc.provider.config;

import com.csdj.sc.common.aop.AbstractRoleCheck;
import com.csdj.sc.common.constant.HeaderConstant;
import com.csdj.sc.common.entity.User;
import com.csdj.sc.provider.service.IUserService;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@Component
public class UserRoleCheck extends AbstractRoleCheck {
    @Resource
    private IUserService userService;
    @Override
    public boolean checkRoles(int[] roles) {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes)requestAttributes).getRequest();
        String uidStr = request.getHeader(HeaderConstant.HEAD_UID);
        if(StringUtils.hasText(uidStr)){
            int uid = Integer.valueOf(uidStr);
            User user = userService.getById(uid);
            if(user != null){
                //遍历注解中所有要求角色，只要一个匹配就通过
                for(int roleId : roles){
                    if(roleId == user.getRoleId()){
                        return true;
                    }
                }
            }
        }
        return false;
    }
}
